"use client";

import type React from "react";

import { useState, useEffect, useRef, useCallback } from "react";
import { useUser } from "@/hooks/useUser";
import { useWallet } from "@/hooks/useWallet";
import ChatMessage from "./chat-message";
import WalletModal from "./wallet-modal";
import EmojiPicker from "./emoji-picker";
import { formatAddress } from "@/utils/wallet";
import { Smile } from "lucide-react";
import type { Database } from "@/lib/database.types";

// Constants for WebSocket
const LOCAL_STORAGE_USER_ID_KEY = "chatUserID";
const KEEP_ALIVE_INTERVAL = 45000; // Send keepalive every 45 seconds
const WEBSOCKET_URL_BASE =
  process.env.NEXT_PUBLIC_WEBSOCKET_URL || "wss://ai369.xyz:8011/ws";
const ONLINE_USERS_STORAGE_KEY = "onlineUsers";

type Message = Database["public"]["Tables"]["messages"]["Row"] & {
  anonymous_users: {
    nickname: string;
    avatar_seed: string;
  };
};

// WebSocket message interface
interface WSMessage {
  type:
    | "chat"
    | "user_join"
    | "user_leave"
    | "info"
    | "error"
    | "system"
    | "keepalive";
  message?: string;
  user?: string;
  timestamp?: number;
  user_id?: string;
  content?: string; // Added for compatibility with existing Message type
  nickname?: string;
  avatar_seed?: string;
}

export default function RetroChat() {
  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isWalletModalOpen, setIsWalletModalOpen] = useState(false);
  const [showWalletDetails, setShowWalletDetails] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isConnected, setIsConnected] = useState(false);
  const { user } = useUser();
  const {
    connected,
    account,
    isConnecting,
    isWalletInstalled,
    connectWallet,
    disconnect,
    error: walletError,
  } = useWallet();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // WebSocket references
  const ws = useRef<WebSocket | null>(null);
  const reconnectAttempts = useRef(0);
  const maxReconnectAttempts = 5;
  const reconnectTimeoutId = useRef<NodeJS.Timeout | null>(null);
  const keepAliveIntervalId = useRef<NodeJS.Timeout | null>(null);
  const [webSocketId, setWebSocketId] = useState<string | null>(null);
  const connectedUsers = useRef<Set<string>>(new Set());
  // 使用更可靠的方式跟踪已发送的消息
  const sentMessages = useRef<Map<string, number>>(new Map());

  // Function to log all online users for debugging
  const logOnlineUsers = useCallback(() => {
    try {
      const onlineUsersStr = localStorage.getItem(ONLINE_USERS_STORAGE_KEY);
      if (onlineUsersStr) {
        const onlineUsers = JSON.parse(onlineUsersStr);
        console.log("[DEBUG] Current online users:", onlineUsers);
      } else {
        console.log("[DEBUG] No online users in localStorage");
      }
    } catch (e) {
      console.error(
        "[DEBUG] Failed to parse online users from localStorage",
        e
      );
    }
  }, []);

  // Function to update online users list in localStorage
  const updateOnlineUsersList = useCallback(
    (userId: string, nickname: string) => {
      if (!userId || !nickname) {
        console.error(
          "Cannot update online users list with empty userId or nickname",
          { userId, nickname }
        );
        return;
      }

      try {
        // Add to our in-memory set
        connectedUsers.current.add(userId);

        // Get current online users from localStorage
        const onlineUsersStr = localStorage.getItem(ONLINE_USERS_STORAGE_KEY);
        let onlineUsers: Record<
          string,
          { nickname: string; lastSeen: number }
        > = {};

        if (onlineUsersStr) {
          try {
            onlineUsers = JSON.parse(onlineUsersStr);
          } catch (e) {
            console.error("Failed to parse online users from localStorage", e);
            onlineUsers = {};
          }
        }

        // Update the user's entry
        onlineUsers[userId] = {
          nickname: nickname,
          lastSeen: Date.now(),
        };
        console.debug(onlineUsers)
        // Save back to localStorage
        localStorage.setItem(
          ONLINE_USERS_STORAGE_KEY,
          JSON.stringify(onlineUsers)
        );

        // Create a custom event to notify other components of the user list change
        const userChangeEvent = new CustomEvent("onlineUsersChanged", {
          detail: { userId, nickname, action: "join" },
        });
        window.dispatchEvent(userChangeEvent);

        // Debug log
        console.log(
          `[User Status] Updated user ${nickname} (${userId}) in online users list`
        );
        logOnlineUsers();
      } catch (e) {
        console.error("Failed to update online users list", e);
      }
    },
    [logOnlineUsers]
  );

  // Function to remove a user from online users list
  const removeFromOnlineUsersList = useCallback(
    (userId: string) => {
      if (!userId) {
        console.error("Cannot remove user with empty userId");
        return;
      }

      try {
        // Remove from our in-memory set
        connectedUsers.current.delete(userId);

        // Get current online users from localStorage
        const onlineUsersStr = localStorage.getItem(ONLINE_USERS_STORAGE_KEY);
        if (!onlineUsersStr) return;

        let onlineUsers: Record<string, { nickname: string; lastSeen: number }>;
        try {
          onlineUsers = JSON.parse(onlineUsersStr);

          // Get the nickname before removing for logging
          const nickname = onlineUsers[userId]?.nickname || "Unknown User";

          // Remove the user
          delete onlineUsers[userId];

          // Save back to localStorage
          localStorage.setItem(
            ONLINE_USERS_STORAGE_KEY,
            JSON.stringify(onlineUsers)
          );

          // Create a custom event to notify other components of the user list change
          const userChangeEvent = new CustomEvent("onlineUsersChanged", {
            detail: { userId, nickname, action: "leave" },
          });
          window.dispatchEvent(userChangeEvent);

          // Debug log
          console.log(
            `[User Status] Removed user ${nickname} (${userId}) from online users list`
          );
          logOnlineUsers();
        } catch (e) {
          console.error(
            "Failed to parse or update online users in localStorage",
            e
          );
        }
      } catch (e) {
        console.error("Failed to remove user from online users list", e);
      }
    },
    [logOnlineUsers]
  );

  // Clear all timers (reconnect + keepalive)
  const clearTimers = useCallback(() => {
    if (reconnectTimeoutId.current) {
      clearTimeout(reconnectTimeoutId.current);
      reconnectTimeoutId.current = null;
    }
    if (keepAliveIntervalId.current) {
      clearInterval(keepAliveIntervalId.current);
      keepAliveIntervalId.current = null;
    }
  }, []);

  // Send keepalive message
  const sendKeepAlive = () => {
    if (ws.current && ws.current.readyState === WebSocket.OPEN) {
      try {
        const keepAliveMsg = JSON.stringify({ type: "keepalive" });
        ws.current.send(keepAliveMsg);
      } catch (error) {
        console.error("[KeepAlive] Failed to send keepalive:", error);
      }
    } else {
      clearTimers();
    }
  };

  // Connect WebSocket
  const connectWebSocket = useCallback(() => {
    clearTimers();

    if (
      ws.current &&
      (ws.current.readyState === WebSocket.OPEN ||
        ws.current.readyState === WebSocket.CONNECTING)
    ) {
      if (ws.current.readyState === WebSocket.OPEN) setIsConnected(true);
      return;
    }

    console.log(
      `[Connect] Attempting to connect WebSocket to ${WEBSOCKET_URL_BASE}... (Attempt ${
        reconnectAttempts.current + 1
      })`
    );
    setLoading(true);
    setIsConnected(false);

    try {
      ws.current = new WebSocket(WEBSOCKET_URL_BASE);
    } catch (error) {
      console.error("[Connect] Failed to create WebSocket:", error);
      setError("Failed to connect to chat server");
      if (reconnectAttempts.current < maxReconnectAttempts) {
        reconnectAttempts.current++;
        const delay = Math.pow(2, reconnectAttempts.current) * 1000;
        reconnectTimeoutId.current = setTimeout(connectWebSocket, delay);
      } else {
        setError("Could not establish connection to chat server");
      }
      setLoading(false);
      return;
    }

    ws.current.onopen = () => {
      console.log("[WS OnOpen] WebSocket connection successful!");
      setIsConnected(true);
      setLoading(false);
      setError(null);
      reconnectAttempts.current = 0;
      clearTimers();
      keepAliveIntervalId.current = setInterval(
        sendKeepAlive,
        KEEP_ALIVE_INTERVAL
      );
      console.log(
        `[WS OnOpen] Started keepalive timer (interval: ${KEEP_ALIVE_INTERVAL}ms).`
      );

      // Restore user ID if available
      const savedUserId = localStorage.getItem(LOCAL_STORAGE_USER_ID_KEY);
      if (savedUserId) {
        console.log(
          "[Init] Retrieved last known User ID from localStorage:",
          savedUserId
        );
        setWebSocketId(savedUserId);
      }
      logOnlineUsers();

      // Update own user status when WebSocket connection established and user is available
      if (user && user.id) {
        updateOnlineUsersList(user.id, user.nickname);
      }
    };

    ws.current.onmessage = async (event) => {
      let dataToParse: string | null = null;
      try {
        if (event.data instanceof Blob) {
          dataToParse = await event.data.text();
        } else if (typeof event.data === "string") {
          dataToParse = event.data;
        } else if (event.data instanceof ArrayBuffer) {
          dataToParse = new TextDecoder().decode(event.data);
        } else {
          console.warn(
            "[WS OnMessage] Received unexpected WebSocket data type:",
            typeof event.data
          );
          return;
        }

        if (dataToParse) {
          const receivedData: WSMessage = JSON.parse(dataToParse);

          if (receivedData.type === "keepalive") return; // Ignore keepalive messages

          // Handle user ID assignment from server
          if (receivedData.type === "system" && receivedData.user_id) {
            const serverUserId = receivedData.user_id;
            console.log(
              "[WS OnMessage] Assigned User ID from server:",
              serverUserId
            );
            setWebSocketId(serverUserId);
            try {
              localStorage.setItem(LOCAL_STORAGE_USER_ID_KEY, serverUserId);

              // Add user ID to connected users set
              if (receivedData.user) {
                updateOnlineUsersList(receivedData.user_id, receivedData.user);
              }
            } catch (storageError) {
              console.error(
                "[WS OnMessage] Failed to save User ID to localStorage:",
                storageError
              );
            }
          }

          // Handle user join events
          if (
            receivedData.type === "user_join" &&
            receivedData.user &&
            receivedData.user_id
          ) {
            updateOnlineUsersList(receivedData.user_id, receivedData.user);
          }

          // Handle user leave events
          if (receivedData.type === "user_leave" && receivedData.user_id) {
            removeFromOnlineUsersList(receivedData.user_id);
          }

          // Convert websocket message to compatible format for our UI
          if (receivedData.type === "chat") {
            // Create a unique message ID based on content and timestamp
            const messageId = `ws-${receivedData.user_id}-${
              receivedData.timestamp || Date.now()
            }-${Math.random().toString(36).substr(2, 9)}`;

            // 改进的重复消息检测逻辑
            if (user && receivedData.nickname === user.nickname) {
              const messageContent =
                receivedData.message || receivedData.content || "";
              const messageSignature = `${receivedData.user_id}:${messageContent}`;

              // 检查发送时间戳是否在我们的缓存中
              const now = Date.now();

              return; // 跳过处理这条重复消息
            }

            const newMessage: Message = {
              id: messageId,
              content: receivedData.message || receivedData.content || "",
              created_at: receivedData.timestamp
                ? new Date(receivedData.timestamp * 1000).toISOString()
                : new Date().toISOString(),
              user_id: receivedData.user_id || receivedData.user || "unknown",
              anonymous_users: {
                nickname:
                  receivedData.nickname || receivedData.user || "Unknown User",
                avatar_seed:
                  receivedData.avatar_seed || receivedData.user_id || "default",
              },
            };

            setMessages((prevMessages) => {
              // 再次检查重复，基于ID
              if (!prevMessages.some((msg) => msg.id === newMessage.id)) {
                return [...prevMessages, newMessage];
              }
              return prevMessages;
            });

            // Scroll to bottom for new messages
            setTimeout(() => {
              if (messagesEndRef.current) {
                messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
              }
            }, 100);
          } else if (
            receivedData.type === "info" ||
            receivedData.type === "error"
          ) {
            // Handle system messages by adding them in a format compatible with our UI
            const systemMessage: Message = {
              id: `system-${Date.now()}-${Math.random()
                .toString(36)
                .substr(2, 9)}`,
              content: receivedData.message || "System notification",
              created_at: receivedData.timestamp
                ? new Date(receivedData.timestamp * 1000).toISOString()
                : new Date().toISOString(),
              user_id: "system",
              anonymous_users: {
                nickname: "System",
                avatar_seed: "system",
              },
            };

            setMessages((prevMessages) => [...prevMessages, systemMessage]);
          }
        }
      } catch (error) {
        console.error(
          "[WS OnMessage] Failed to process or parse received message:",
          error
        );
      }
    };

    ws.current.onclose = (event) => {
      console.log(
        `[WS OnClose] WebSocket connection closed: Code=${event.code}, Reason='${event.reason}', WasClean=${event.wasClean}`
      );
      setIsConnected(false);
      clearTimers();

      let closeMessage = "Connection closed";
      if (event.code === 1000) {
        closeMessage = "Left the chat room";
      } else if (event.reason) {
        closeMessage = `Connection closed: ${event.reason}`;
      } else if (event.code === 1006) {
        closeMessage = "Connection lost";
      } else if (event.code === 1002) {
        closeMessage = "Connection error (Protocol violation)";
      }

      // Add system message about connection close
      const systemMessage: Message = {
        id: `system-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        content: closeMessage,
        created_at: new Date().toISOString(),
        user_id: "system",
        anonymous_users: {
          nickname: "System",
          avatar_seed: "system",
        },
      };

      setMessages((prevMessages) => [...prevMessages, systemMessage]);

      if (
        event.code !== 1000 &&
        reconnectAttempts.current < maxReconnectAttempts
      ) {
        reconnectAttempts.current++;
        const delay = Math.min(
          Math.pow(2, reconnectAttempts.current) * 1000,
          30000
        );
        console.log(
          `[WS OnClose] Attempting reconnect in ${
            delay / 1000
          } seconds (Attempt ${reconnectAttempts.current})...`
        );
        reconnectTimeoutId.current = setTimeout(connectWebSocket, delay);
      } else if (reconnectAttempts.current >= maxReconnectAttempts) {
        console.error("[WS OnClose] Maximum reconnect attempts reached.");
        setError("Could not reconnect to chat server");
        setLoading(false);
      }
    };

    ws.current.onerror = (error) => {
      console.error("[WS OnError] WebSocket error:", error);
      setError("Connection error");
    };
  }, [
    clearTimers,
    logOnlineUsers,
    updateOnlineUsersList,
    removeFromOnlineUsersList,
    user,
  ]);

  // Initialize WebSocket connection
  useEffect(() => {
    connectWebSocket();

    return () => {
      console.log(
        "[Cleanup] RetroChat component unmounting. Closing WebSocket connection..."
      );
      clearTimers();
      reconnectAttempts.current = maxReconnectAttempts;
      if (ws.current) {
        ws.current.onclose = null;
        ws.current.onerror = null;
        ws.current.close(1000, "Component unmounted");
        ws.current = null;
      }
    };
  }, [connectWebSocket, clearTimers]);

  // Update online status when user info changes
  useEffect(() => {
    if (user && user.id && isConnected) {
      updateOnlineUsersList(user.id, user.nickname);
    }
  }, [user, isConnected, updateOnlineUsersList]);

  const handleSendMessage = async (contentToSend?: string) => {
    if (isSubmitting) return;
    setIsSubmitting(true);

    try {
      const messageContent = contentToSend || message;

      if (!messageContent.trim() || !user) {
        setIsSubmitting(false);
        return;
      }

      // Clear input right away
      setMessage("");

      // Create a temporary message for optimistic UI
      const tempId = `temp-${Date.now()}`;
      const tempMessage = {
        id: tempId,
        content: messageContent,
        created_at: new Date().toISOString(),
        user_id: user.id,
        anonymous_users: {
          nickname: user.nickname,
          avatar_seed: user.avatarSeed,
        },
      } as Message;

      // Add to messages immediately for instant feedback
      setMessages((prevMessages) => {
        const newMessages = [...prevMessages, tempMessage].sort(
          (a, b) =>
            new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
        );
        return newMessages;
      });

      // // Scroll to bottom immediately
      // setTimeout(() => {
      //   if (messagesEndRef.current) {
      //     messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
      //   }
      // }, 100);

      // 使用更健壮的方式记录发送的消息，用于防止重复
      const messageSignature = `${user.id}:${messageContent}`;
      sentMessages.current.set(messageSignature, Date.now());

      // Send message through WebSocket instead of fetch
      if (ws.current && ws.current.readyState === WebSocket.OPEN) {
        try {
          const messageData = {
            type: "chat",
            message: messageContent,
            user: user.nickname,
            nickname: user.nickname,
            avatar_seed: user.avatarSeed,
          };
          ws.current.send(JSON.stringify(messageData));
        } catch (error) {
          console.error("[SendMessage] Failed to send message:", error);
          setError("Failed to send message");

          // Remove the temporary message if failed
          setMessages((prevMessages) =>
            prevMessages.filter((msg) => msg.id !== tempId)
          );
          sentMessages.current.delete(messageSignature);
        }
      } else {
        console.warn(
          "[SendMessage] WebSocket is not connected. Cannot send message."
        );
        setError("Connection closed. Cannot send message.");

        // Remove the temporary message if failed
        setMessages((prevMessages) =>
          prevMessages.filter((msg) => msg.id !== tempId)
        );
        sentMessages.current.delete(messageSignature);
      }
    } catch (error) {
      console.error("Error sending message:", error);
      setError("Failed to send message. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleWalletConnect = () => {
    setIsWalletModalOpen(true);
  };

  const handleWalletConnectConfirm = async () => {
    await connectWallet();
    if (!walletError) {
      setIsWalletModalOpen(false);
    }
  };

  const toggleWalletDetails = () => {
    setShowWalletDetails(!showWalletDetails);
  };

  const toggleEmojiPicker = () => {
    setShowEmojiPicker(!showEmojiPicker);
  };

  const handleEmojiSelect = (emoji: string) => {
    // Send the emoji directly to the chat
    handleSendMessage(emoji);
    setShowEmojiPicker(false);
  };

  const handleRetry = () => {
    setError(null);
    setLoading(true);
    connectWebSocket();
  };

  const connectionStatus = isConnected
    ? "Connected to chat server"
    : loading
    ? "Connecting to chat server..."
    : "Disconnected from chat server";

  return (
    <div className="flex-1 flex flex-col p-2">
      <div className="flex justify-between items-center mb-2">
        <div className="text-black text-sm font-bold">
          Chat Room - Main Channel
        </div>
        <div className="flex items-center space-x-2">
          {user && (
            <div className="text-xs mr-2">
              <span className="font-bold">{user.nickname}</span>
              {webSocketId && (
                <span className="text-xs text-gray-500">
                  {" "}
                  (ID: {webSocketId.substring(0, 8)})
                </span>
              )}
            </div>
          )}
          {connected && account ? (
            <div className="relative">
              <button
                onClick={toggleWalletDetails}
                className="win95-button bg-[#c0c0c0] text-black px-2 py-1 text-xs flex items-center"
              >
                <span className="truncate max-w-[80px]">
                  {formatAddress(account.solanaAddress)}
                </span>
              </button>

              {showWalletDetails && (
                <div className="absolute right-0 mt-1 w-64 bg-[#c0c0c0] win95-border z-10">
                  <div className="p-2 text-xs border-b border-[#808080]">
                    <div className="font-bold">Solana Address:</div>
                    <div className="break-all">{account.solanaAddress}</div>
                  </div>

                  {account.solanaBalance && (
                    <div className="p-2 text-xs border-b border-[#808080]">
                      <div className="font-bold">Balance:</div>
                      <div>{account.solanaBalance} SOL</div>
                    </div>
                  )}

                  <button
                    onClick={() => {
                      disconnect();
                      setShowWalletDetails(false);
                    }}
                    className="w-full text-left p-2 text-sm hover:bg-[#000080] hover:text-white"
                  >
                    Disconnect
                  </button>
                </div>
              )}
            </div>
          ) : (
            <button
              onClick={handleWalletConnect}
              className="win95-button bg-[#c0c0c0] text-black px-2 py-1 text-xs"
            >
              Connect Wallet
            </button>
          )}
        </div>
      </div>

      {/* Status indicator for WebSocket connection */}
      <div className="flex justify-between items-center mb-2">
        <div className="text-xs flex items-center">
          <span
            className={`inline-block w-2 h-2 rounded-full mr-1 ${
              isConnected
                ? "bg-green-500"
                : loading
                ? "bg-yellow-500"
                : "bg-red-500"
            }`}
          ></span>
          <span>{connectionStatus}</span>
        </div>
      </div>

      {/* Fixed height chat container with proper scrolling */}
      <div
        className="win95-inset bg-white mb-2"
        style={{
          height: "850px",
          overflowY: "scroll",
          overflowX: "hidden",
          display: "block",
        }}
      >
        {loading && messages.length === 0 ? (
          <div className="flex justify-center items-center h-full">
            <div className="text-center">
              <div
                className="win95-border bg-[#c0c0c0] p-2 mb-2 mx-auto"
                style={{ width: "30px", height: "30px" }}
              >
                <div className="animate-pulse w-full h-full bg-[#000080]"></div>
              </div>
              <span>Connecting to chat server...</span>
            </div>
          </div>
        ) : error && messages.length === 0 ? (
          <div className="flex flex-col justify-center items-center h-full">
            <div className="text-center mb-4">
              <p className="text-red-600 mb-2">{error}</p>
              <button
                onClick={handleRetry}
                className="win95-button bg-[#c0c0c0] px-3 py-1"
              >
                Retry
              </button>
            </div>
          </div>
        ) : messages.length === 0 ? (
          <div className="flex justify-center items-center h-full">
            <span>No messages yet. Be the first to say hello!</span>
          </div>
        ) : (
          <div className="p-2">
            {messages.map((msg) => (
              <ChatMessage
                key={msg.id}
                content={msg.content}
                timestamp={msg.created_at}
                user={{
                  nickname: msg.anonymous_users?.nickname || "Unknown User",
                  avatarSeed: msg.anonymous_users?.avatar_seed || "default",
                }}
                currentUser={user}
              />
            ))}
            <div ref={messagesEndRef} />
          </div>
        )}
      </div>

      <div className="flex mb-2 relative">
        <div className="relative">
          <button
            className="win95-button bg-[#c0c0c0] p-1 mr-1"
            onClick={toggleEmojiPicker}
            aria-label="Select emoji"
            disabled={!isConnected}
          >
            <Smile size={18} />
          </button>

          {showEmojiPicker && (
            <EmojiPicker
              onEmojiSelect={handleEmojiSelect}
              onClose={() => setShowEmojiPicker(false)}
            />
          )}
        </div>

        <input
          type="text"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={
            isConnected ? "Type your message..." : "Waiting for connection..."
          }
          className="flex-1 win95-inset bg-white text-black border-0 p-1 text-sm"
          disabled={!user || isSubmitting || !isConnected}
        />
        <button
          onClick={() => handleSendMessage()}
          className="win95-button bg-[#c0c0c0] px-2 py-1 ml-1 text-sm"
          disabled={!user || isSubmitting || !message.trim() || !isConnected}
        >
          Send
        </button>
      </div>

      <div className="flex justify-center space-x-2">
        {connected && account && (
          <button className="win95-button bg-[#c0c0c0] px-2 py-1 text-sm flex items-center">
            <span className="text-xs">
              SOL: {formatAddress(account.solanaAddress)}
            </span>
          </button>
        )}
      </div>

      {/* Wallet Connection Modal */}
      <WalletModal
        isOpen={isWalletModalOpen}
        onClose={() => setIsWalletModalOpen(false)}
        onConnect={handleWalletConnectConfirm}
        isWalletInstalled={isWalletInstalled}
        isConnecting={isConnecting}
        error={walletError}
      />
    </div>
  );
}
